package com.wonders.frame.controller;

import com.gcr.server.response.Response;
import com.wonders.frame.common.Enum.ResponseCodeEnum;
import com.wonders.frame.common.Enum.SessionKeyEnum;
import com.wonders.frame.common.ParamsForm;
import com.wonders.frame.common.QueryForm;
import com.wonders.frame.controller.core.CoreController;
import com.wonders.frame.entity.AuthAccount;
import com.wonders.frame.entity.AuthOrga;
import com.wonders.frame.entity.form.AuthAccountForm;
import com.wonders.frame.entity.form.AuthUserForm;
import com.wonders.frame.entity.form.PasswordForm;
import com.wonders.frame.service.AuthAccountService;
import com.wonders.frame.service.AuthOrgaService;
import com.wonders.frame.service.Core.CoreCurdService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

@RestController
@RequestMapping("/authAccount")
public class AuthAccountController extends CoreController<AuthAccount> {
    Logger log = LoggerFactory.getLogger(AuthAccountController.class);
    @Autowired
    private AuthAccountService service;
    @Autowired
    private AuthOrgaService orgaService;

    @Override
    protected CoreCurdService getService() {
        return service;
    }

    private final ReentrantLock lock=new ReentrantLock();


    @RequestMapping("getList1")
    public Response getListByParams1(@RequestBody QueryForm form, HttpServletRequest request){
        Map<String, Object> params = form.getParams();
        HttpSession session = request.getSession();
        AuthAccount acc =  (AuthAccount)session.getAttribute(SessionKeyEnum.USERINFO.name());
        List<AuthOrga> authOrgas = orgaService.findAllOrgaByOrgaId(acc.getDeptId());
        String deptId = new String();
        for(AuthOrga authOrga : authOrgas){
            if(authOrga.getId().equals(acc.getDeptId())) {
                deptId=deptId+(authOrga.getId());
            }else {
                deptId=deptId+authOrga.getId()+",";
            }
        }
        params.put("deptId_in",deptId);
        return getResponseWithoutMsg(getService().findAllByParams(form, request), ResponseCodeEnum.SUCCESS.getCode());
    }


    @RequestMapping("save")
    public Response save(@RequestBody AuthAccountForm accountForm, HttpServletRequest request) {
        try {
            lock.lock();
            HttpSession session = request.getSession();
            if(service.checkUniqueAccount(accountForm)){
                return getResponseWithoutMsg(service.save(accountForm, ""/*acc.getUser().getUserName()*/), ResponseCodeEnum.SUCCESS.getCode());
            }else{
                return errorResponse(ResponseCodeEnum.ACCOUNT_REPEAT,null);
            }
        }catch (Exception e){
            e.printStackTrace();
            return errorResponse();
        }finally {
            lock.unlock();
        }
    }

    @GetMapping("/getAccount")
    public Response getAccount(String userId){
        return successResponse(service.findByUserId(userId));
    }


    /**
     * 查询员工列表
     * @return
     */
    @PostMapping("/getUserList")
    public Response getUserList(HttpServletRequest request,@RequestBody AuthUserForm authUserForm){
        try {
            return successResponse(service.getUserList(authUserForm));
        }catch (Exception e){
            e.printStackTrace();
            return errorResponse();
        }
    }


    @GetMapping("/getUserByOrgaId")
    public Response getUserByOrgaId(String orgaId,HttpServletRequest request){
        try {
            //service.findAllByParams(new HashMap<String, Object>(),request);
            return successResponse(service.getUserByOrgaId(orgaId));
        }catch (Exception e){
            e.printStackTrace();
            return errorResponse();
        }
    }

    @RequestMapping("/resetPassword")
    public Response resetPassword(String id){
        try {
            service.resetPassword(id);
            return successResponse(null);
        }catch (Exception e){
            e.printStackTrace();
            return errorResponse();
        }
    }

    @PostMapping("/updatePassword")
    public Response updatePassword(@RequestBody PasswordForm passwordForm){
        try {
            log.info("request:authAccount/updatePassword");
            log.info("PasswordForm="+passwordForm.toString());
            //是原密码才能修改
            if(!service.isOldPassword(passwordForm.getId(),passwordForm.getOldPassword())){
                return errorResponse(ResponseCodeEnum.OLDPASSWORD_MISMATCH,null);
            }
            service.updatePassword(passwordForm);
            return successResponse(null);
        }catch (Exception e){
            e.printStackTrace();
            return errorResponse();
        }
    }


    //获得成员列表
    @PostMapping("/getMember")
    public Response getMember(@RequestBody ParamsForm paramsForm){
        try {
            List<AuthAccount> list=service.findAllByParams(paramsForm.getParams(),null,null );
            return successResponse(service.getMember(list));
        }catch (Exception e){
            e.printStackTrace();
            return errorResponse();
        }
    }

    //注销
    @PostMapping("/accountLogout")
    public Response accountLogout(String id){
        try {
            log.info("authAccount/accountLogout");
            log.info("id="+id);
            return successResponse(service.accountLogout(id));
        }catch (Exception e){
            e.printStackTrace();
            return errorResponse();
        }
    }

    //启用
    @PostMapping("/accountEnable")
    public Response accountEnable(String id){
        try {
            log.info("authAccount/accountEnable");
            log.info("id="+id);
            return successResponse(service.accountEnable(id));
        }catch (Exception e){
            e.printStackTrace();
            return errorResponse();
        }
    }

    //获取权限
    @GetMapping("/getPermissionByAccountId")
    public Response getPermissionByAccountId(String accountId){
        try {
            return successResponse(service.getPermissionByAccountId(accountId));
        }catch (Exception e){
            e.printStackTrace();
            return errorResponse();
        }
    }

    //删除用户
    @PostMapping("/deleteAccounts")
    public Response deleteAccounts(@RequestBody AuthAccountForm accountForm){
        try {
            service.deleteAccounts(accountForm.getAccountsId());
            return successResponse(null);
        }catch (Exception e){
            e.printStackTrace();
            return errorResponse();
        }
    }

    //修改用户机构
    @PostMapping("/changeAccountOrga")
    public Response changeAccountOrga(@RequestBody AuthAccountForm accountForm){
        try {
            service.changeAccountOrga(accountForm.getAccountsId(),accountForm.getChangeOrgaId());
            return successResponse(null);
        }catch (Exception e){
            e.printStackTrace();
            return errorResponse();
        }
    }

    //解锁
    @GetMapping("/unLock")
    public Response accountUnlock(String id){
        try {
            log.info("authAccount/accountUnlock");
            log.info("id="+id);
            return successResponse(service.accountUnlock(id));
        }catch (Exception e){
            e.printStackTrace();
            return errorResponse();
        }
    }

    //删除用户
    @RequestMapping("delete1")
    public Response delete1(String id) {
        service.deleteAccount(id);
        return getResponseWithCode(ResponseCodeEnum.SUCCESS.getCode());
    }
}
